<?php

class Chat extends Core_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->model('chat_model');
        $this->load->helper('text');
        $this->load->helper('utils');
        
        if (empty($_SESSION['message']) == FALSE) {
            $this->data['message'] = $_SESSION['message'];
            unset($_SESSION['message']);
        }

        if (empty($_SESSION['error']) == FALSE) {
            $this->data['error'] = $_SESSION['error'];
            unset($_SESSION['error']);
        }

        if (empty($_SESSION['params_post']) == FALSE) {
            $this->data['params_post'] = $_SESSION['params_post'];
            unset($_SESSION['params_post']);
        }
    }

    public function index() {
        $chat = $this->chat_model->get();

        $this->data['chat'] = $chat;
        $this->template->parse_view('content', 'frontend/chat/index', $this->data);
        $this->template->render();
    }

    public function create() {
        $params = $this->input->post(NULL, TRUE);
        if (empty($params) == FALSE) {
            $data_insert = array(
                'fb_id' => $_SESSION['facebook_id'],
                'key' => $params['key'],
                'value' => $params['value'],
                'status' => 1,
            );
            $insert_id = $this->chat_model->create($data_insert);
            $_SESSION['message'] = 'Thêm nội dung thành công';            
            $_SESSION['params_post']['modify_id'] = $insert_id;
            redirect(base_url('chat'));
        } else {
            redirect(base_url());
        }
    }

    public function update($id) {
        $params = $this->input->post();
        if (empty($params) == FALSE) {
            $data_update = array(
                'key' => $params['key'],
                'value' => $params['value'],
            );
            $this->chat_model->update($id, $data_update);
            $_SESSION['message'] = 'Cập nhật nội dung thành công';            
            $_SESSION['params_post']['modify_id'] = $id;
            redirect(base_url('chat'));
        } else {
            $id = intval($id);
            $where = array('id' => $id);
            $chat = $this->chat_model->get($where);

            $this->data['chat'] = current($chat);
            $this->template->parse_view('content', 'frontend/chat/update', $this->data);
            $this->template->render();
        }
    }
    
    public function update_status() {
        $params = $this->input->post();
        if (empty($params) == FALSE) {
            $id = intval($params['id']);
            $data_update['status'] = $params['status'];
            
            $this->load->model('chat_model');
            $this->chat_model->update($id, $data_update);
        }
    }

}
